package com.edu.bean;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class MyIOC {

    //需要一条属性来存多个 不确定类型的对象
    Map<String,Object> map = new HashMap();

    public MyIOC(String path){
        Properties pro = new Properties();//用于读配置文件（真正的Spring容器 需要去解析xml格式 dom4j）
        InputStream ins = MyIOC.class.getClassLoader().getResourceAsStream(path);
        try {
            if(ins == null){
                System.out.println("配置文件不存在");
                return;
            }
            pro.load(ins);
            Set<String> keys = pro.stringPropertyNames();
            for (String key : keys) {
                String className = pro.getProperty(key);
                Class clazz = Class.forName(className);
                Constructor constructor = clazz.getDeclaredConstructor();
                constructor.setAccessible(true);
                Object o = constructor.newInstance();
                map.put(key,o);
            }

        } catch (IOException e) {
            System.out.println("配置文件不可读写，或配置文件不存在");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            System.out.println("类名不存在");
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public Object getBean(String beanId){
        return map.get(beanId);
    }

    public Object getBean(Class clazz){
        Set<String> keySet = map.keySet();
        for (String s : keySet) {
            if(map.get(s).getClass()==clazz){
                return map.get(s);
            }
        }
        return null;
    }
}
